const Koa = require('koa')
const path = require('path')
const morgan = require('koa-morgan')
const koaBody = require('koa-body')
const Router = require('koa-router')
const cors = require('koa-cors')
const compress = require('koa-compress')
const koaStatic = require('koa-static')
const utils = require('./utils')
const env = require('./env')
const logger = require('./log').logger
const app = new Koa()
const router = new Router()

require('./mongoose')
require('./redis')

class App {
  constructor() {
    this.app = app
  }

  init() {
    this.initDB()
    this.initMiddleWare()
    this.initRouter()
    this.listen(env.port)
  }

  initDB() {
    utils.globPath('./modules/*/*.model.js', paths => {
      paths.forEach(path => {
        require(path)
      })
    })
    console.log('********** Model is Ready **********')
  }

  initMiddleWare() {
    this.app.use(morgan('dev'))
    this.app.use(cors())
    this.app.use(compress())
    this.app.use(koaStatic(path.resolve(env.staticPath)))
    this.app.use(koaBody({
      multipart: true
    }))
    this.app.use(logger)
    console.log('********** MiddleWare is Ready **********')
  }

  initRouter() {
    utils.globPath('./modules/*/*.router.js', paths => {
      paths.forEach(path => {
        require(path)(router)
      })
    })
    app.use(router.routes()).use(router.allowedMethods())
    console.log('********** Router is Ready **********')
  }

  listen(port) {
    this.app.listen(port, () => {
      console.log(`Server is running on ${port} !`)
    })
  }

}

module.exports = new App()